//
//  QXEmoticonKeyboardVC.swift
//  图文混排
//
//  Created by QinXin on 15/7/7.
//  Copyright © 2015年 labi3285_Lab. All rights reserved.
//

import UIKit

class QXEmoticonKeyboardVC: UIViewController {
    
    
    var didSelectEmoticonCallBack: (emoticon: QXEmoticon) -> ()
    init(didSelectEmoticon: (emoticon: QXEmoticon) -> ()) {
        didSelectEmoticonCallBack = didSelectEmoticon
        super.init(nibName: nil, bundle: nil)
    }

    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    func selectItem(item: UIBarButtonItem) {
        let idxPath = NSIndexPath(forItem: 0, inSection: item.tag)
        collectionView.scrollToItemAtIndexPath(idxPath, atScrollPosition: UICollectionViewScrollPosition.Left, animated: true)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.backgroundColor = UIColor.redColor()
        
        QXEmoticonPackage.packages()
        
        setupUIs()
        setupToolBar()
        setupCollectionView()
    }
    
    private func setupUIs() {
        view.addSubview(toolBar)
        view.addSubview(collectionView)
        
        toolBar.translatesAutoresizingMaskIntoConstraints = false
        collectionView.translatesAutoresizingMaskIntoConstraints = false
        
        var cons = [NSLayoutConstraint]()
        let viewDic = [
            "collectionView": collectionView,
            "toolBar": toolBar,
        ]
        cons += NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[collectionView]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: viewDic)
        cons += NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[toolBar]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: viewDic)
        cons += NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[collectionView]-0-[toolBar(44)]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: viewDic)

        view.addConstraints(cons)
        
    }
    
    private func setupToolBar() {
        var items = [UIBarButtonItem]()
        var idx = 0
        for s in emoticonPackages {
            let item = UIBarButtonItem(title: s.groupName, style: UIBarButtonItemStyle.Plain, target: self, action: "selectItem:")
            item.tag = idx++
            items.append(item)
            items.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
        }
        items.removeLast()
        toolBar.items = items
    }
    
    private func setupCollectionView() {
        collectionView.backgroundColor = UIColor.whiteColor()
        collectionView.showsHorizontalScrollIndicator = false
        collectionView.dataSource = self
        collectionView.pagingEnabled = true
        collectionView.registerClass(QXEmoticonCell.self, forCellWithReuseIdentifier: "QXEmoticonCell")
        collectionView.delegate = self
    }
    

    private lazy var toolBar = UIToolbar()
    private lazy var collectionView: UICollectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: QXEmoticonLayout())
    
    // MARK: 私有布局类
    private class QXEmoticonLayout: UICollectionViewFlowLayout {
        
        // 这个方法在布局之前会调用一次
        override private func prepareLayout() {
            super.prepareLayout()
            // 图标一行固定有 7 个
            let wh = collectionView!.bounds.width / 7
            itemSize = CGSize(width: wh, height: wh)
            minimumInteritemSpacing = 0
            minimumLineSpacing = 0
            
            // 居中（这里写0.4，是为了适配4s， 浮点精度问题）
            let y = (collectionView!.bounds.height - 3 * wh) * 0.4
            sectionInset = UIEdgeInsets(top: y, left: 0, bottom: y, right: 0)
            
            scrollDirection = UICollectionViewScrollDirection.Horizontal
        }
        
        
    }
    
    private lazy var emoticonPackages: [QXEmoticonPackage] = QXEmoticonPackage.packages()
    
}


extension QXEmoticonKeyboardVC: UICollectionViewDataSource, UICollectionViewDelegate {
    
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return emoticonPackages.count
    }
    
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return emoticonPackages[section].emoticons?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier("QXEmoticonCell", forIndexPath: indexPath) as! QXEmoticonCell
        cell.emoticon = emoticonPackages[indexPath.section].emoticons![indexPath.item]
        return cell
    }
    
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        
        let emoticon = emoticonPackages[indexPath.section].emoticons![indexPath.item]
        
        // 记录表情的使用次数
        if emoticon.chs != nil || emoticon.emoji != nil {
            emoticon.useCount++
            emoticonPackages[0].addFavoriteEmoticon(emoticon)
        }
        
        didSelectEmoticonCallBack(emoticon: emoticon)
    }
    
}

/// 表情自定义cell
private class QXEmoticonCell: UICollectionViewCell {
    
    /// 表情模型
    var emoticon: QXEmoticon? {
        didSet {
            if let path = emoticon?.imagePath {
                iconBtn.setImage(UIImage(contentsOfFile: path), forState: UIControlState.Normal)
            } else {
                // 解决表情重用问题
                iconBtn.setImage(nil, forState: UIControlState.Normal)
            }
            // 只有有emoji的地方才会创建
            iconBtn.setTitle(emoticon?.emoji, forState: UIControlState.Normal)
            
            if emoticon!.isRemoveBtn {
                iconBtn.setImage(UIImage(named: "compose_emotion_delete"), forState: UIControlState.Normal)
                iconBtn.setImage(UIImage(named: "compose_emotion_delete_highlighted"), forState: UIControlState.Highlighted)
            }
        }
    }
    
    /// 表情按钮
    private lazy var iconBtn = UIButton()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        addSubview(iconBtn)
        iconBtn.userInteractionEnabled = false
        iconBtn.frame = CGRectInset(bounds, 4, 4)
        iconBtn.titleLabel?.font = UIFont.systemFontOfSize(32)
        backgroundColor = UIColor.clearColor()
    }

    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
 
}
